<template>
  <el-dialog
    title="项目月进度统计"
    :visible.sync="show"
    width="1000px"
    center
    :close-on-click-modal="false"
  >
    <el-form
      ref="form"
      :rules="rules"
      style="padding-top: 10px"
      :model="form"
      label-width="100px"
    >
      <div class="com-form-title">基础信息</div>
      <el-row>
        <el-col :span="8">
          <el-form-item label="项目名称" prop="projectName">
            <!-- <el-input v-model="form.projectName" :disabled="true" /> -->
            <el-input
              v-model="form.projectName"
              readonly
              :disabled="disableForm || optType !== 'add'"
              @click.native="
                optType === 'add' ? (showTargetSetListModal = true) : null
              "
            >
              <i
                slot="suffix"
                class="el-input__icon el-icon-circle-plus-outline"
              />
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="年份" prop="year">
            <!-- <el-input v-model="form.year" :disabled="disableForm" /> -->
            <el-date-picker
              v-model="form.year"
              type="year"
              value-format="yyyy"
              :disabled="disableForm"
              style="width: 100%"
              placeholder="选择年"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="月份" prop="month">
            <!-- <el-input v-model="form.month" :disabled="disableForm" /> -->
            <el-date-picker
              v-model="form.month"
              type="month"
              value-format="MM"
              format="MM"
              :disabled="disableForm"
              placeholder="选择月"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="本月完成金额" prop="thisMonthCompleteAmount">
            <el-input
              v-model="form.thisMonthCompleteAmount"
              :disabled="disableForm"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="进度偏差额" prop="progressDeviation">
            <el-input
              v-model="form.progressDeviation"
              :disabled="disableForm"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="进项税合计" prop="totalInputTax">
            <el-input v-model="form.totalInputTax" :disabled="disableForm" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item
            label="计划完成金额"
            prop="planCompleteAmount"
          >
            <el-input
              v-model="form.planCompleteAmount"
              :disabled="disableForm"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <div style="margin-left: 20px">
            说明：正值为进度较快，负值为进度滞后
          </div>
        </el-col>
      </el-row>

      <com-table
        v-model="selectRow"
        highlight-current-row
        default-expand-all
        :data="targetList"
        :columns="columns"
        :no-page="true"
        height="300"
        row-key="number"
        :tree-props="{ children: 'childrens', hasChildren: 'hasChildren' }"
      >
        <!-- <template v-slot:contractWorkVolume="{row}">
          <el-input v-model="row.contractWorkVolume" />
        </template>
        <template v-slot:contractPrice="{row}">
          <el-input v-model="row.contractPrice" />
        </template>
        <template v-slot:contractAmount="{row}">
          <el-input v-model="row.contractAmount" />
        </template>
        <template v-slot:costPrice="{row}">
          <el-input v-model="row.costPrice" />
        </template>
        <template v-slot:inputTax="{row}">
          <el-input v-model="row.inputTax" />
        </template>
        <template v-slot:handedAmount="{row}">
          <el-input v-model="row.handedAmount" />
        </template>
        <template v-slot:description="{row}">
          <el-input v-model="row.description" />
        </template>
        <template v-slot:finishCount="{row}">
          <el-input v-model="row.finishCount" />
        </template>
        <template v-slot:finishOutValue="{row}">
          <el-input v-model="row.finishOutValue" />
        </template>
        <template v-slot:cost="{row}">
          <el-input v-model="row.cost" />
        </template> -->
        <template v-slot:contractWorkVolume="{ row }">
          <el-input v-model="row.contractWorkVolume" />
        </template>
        <template v-slot:planFinishCount="{ row }">
          <el-input v-model="row.planFinishCount" />
        </template>
        <template v-slot:planFinishAmount="{ row }">
          <el-input v-model="row.planFinishAmount" @input="getProgressDeviation" />
        </template>
        <template v-slot:costUnitPrice="{ row }">
          <el-input v-model="row.costUnitPrice" @input="getThisMonthFinishAmount" />
        </template>
        <template v-slot:inputTax="{ row }">
          <el-input v-model="row.inputTax" @input="getSumInputTax" />
        </template>
        <template v-slot:preMonthTotalFinishAmount="{ row }">
          <el-input v-model="row.preMonthTotalFinishAmount" />
        </template>
        <template v-slot:thisMonthFinishCount="{ row }">
          <el-input v-model="row.thisMonthFinishCount" @input="getThisMonthFinishAmount" />
        </template>
        <template v-slot:thisMonthFinishAmount="{ row }">
          <el-input v-model="row.thisMonthFinishAmount" disabled />
        </template>
        <template v-slot:thisMonthTotalFinishAmount="{ row }">
          <el-input v-model="row.thisMonthTotalFinishAmount" />
        </template>
        <template v-slot:progressDeviation="{ row }">
          <el-input v-model="row.progressDeviation" disabled />
        </template>
      </com-table>
      <el-button
        style="margin-top: 10px"
        type="primary"
        @click="showFileModal = true"
      >附件资料({{ fileList.length }})</el-button>
      <file-uploader
        v-model="fileList"
        :show-modal.sync="showFileModal"
        :disabled="disableForm"
        :can-download="optType === 'detail'"
      />
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="show = false">取 消</el-button>
      <el-button type="primary" @click="saveDoc">确 定</el-button>
    </span>
    <project-list
      :show-modal.sync="showTargetSetListModal"
      @getSelectedRows="getSelectedRows"
    />
  </el-dialog>
</template>

<script>
import {
  addProjectScheduleStatInfo,
  updateProjectScheduleStatInfo,
  getProjectScheduleStatInfoDetail
} from '@/api/planManage'
import { getAreaList } from '@/api/common'
import { workflowStatus } from '@/utils/dicData'
import fileUploader from '@/components/FileUploader'
import ProjectList from '@/components/TreeModal/project2'
import moment from 'moment'
export default {
  name: 'AddProjectScheduleStatInfo',
  components: {
    fileUploader,
    ProjectList
  },
  props: {
    showModal: {
      type: Boolean,
      default: false
    },
    optType: {
      type: String,
      default: 'add'
    },
    dir: {
      type: Object,
      default() {
        return {}
      }
    },
    data: {
      type: Object,
      default() {
        return {}
      }
    }
  },
  data() {
    return {
      showFileModal: false,
      selectRow: null,
      targetList: [],
      workflowStatus,

      addType: '', // same   under
      visible: false,
      showAdd: false,
      selectedNode: null,
      form: {
        projectName: '',
        year: '',
        month: '',
        thisMonthOutValue: '',
        openCumulativeOutValue: '',
        thisMonthCost: '',
        openCumulativeCost: '',
        addWorkflowId: '',
        status: '',
        founderName: '',
        createTime: '',
        thisMonthCompleteAmount: '',
        progressDeviation: '',
        totalInputTax: '',
        planCompleteAmount: ''
      },
      columns: [
        {
          fixed: 'left',
          label: '清单编号',
          prop: 'number',
          width: '150'
        },
        {
          fixed: 'left',
          label: '清单名称',
          prop: 'name',
          width: '200'
        },
        {
          label: '清单单位',
          prop: 'unit'
        },
        {
          label: '合同工程量',
          prop: 'contractWorkVolume',
          slot: 'contractWorkVolume',
          width: '150'
        },
        {
          label: '计划完成数量',
          slot: 'planFinishCount',
          width: '150'
        },
        {
          label: '计划完成金额',
          slot: 'planFinishAmount',
          width: '150'
        },
        {
          label: '成本单价',
          slot: 'costUnitPrice',
          width: '150'
        },
        {
          label: '进项税',
          slot: 'inputTax',
          width: '150'
        },
        {
          label: '上月累计已完成',
          slot: 'preMonthTotalFinishAmount',
          width: '150'
        },
        {
          label: '本月完成量',
          slot: 'thisMonthFinishCount',
          width: '150'
          // thisMonthFinshCount
        },
        {
          label: '本月完成金额',
          slot: 'thisMonthFinishAmount',
          width: '150'
          // thisMonthFinshAmount
        },
        {
          label: '本月累计已完成',
          slot: 'thisMonthTotalFinishAmount',
          width: '150'
        },
        {
          label: '进度偏差金额',
          slot: 'progressDeviation',
          width: '150'
        }
      ],
      showTargetSetListModal: false,
      fileList: [],
      rules: {
        projectName: [
          { required: true, message: '项目名称', trigger: 'change' }
        ]
        // unifiedSocialCreditCode: [
        //   { required: true, message: '统一社会信用代码', trigger: 'change' }
        // ]
      },
      provinceData: [],
      cityData: [],
      total: 0,
      total2: 0,
      total3: 0
    }
  },
  computed: {
    disableForm() {
      return this.optType === 'detail'
    },
    show: {
      get() {
        return this.showModal
      },
      set(val) {
        this.$emit('update:showModal', val)
      }
    }
  },
  watch: {
    showModal(val) {
      if (val && this.optType !== 'add') {
        this.getDocDetail(this.data.id)
        this.$nextTick(() => {
          Object.keys(this.form).forEach((key) => {
            const source = this.data[key]
            if (typeof source === 'boolean') {
              this.form[key] = source ? 1 : 0
            } else {
              this.form[key] = source
            }
          })
        })
      } else if (!val) {
        this.fileList = []
        this.targetList = []
        this.$refs.form.resetFields()
      }
    }
  },
  mounted() {
    this.getRegionData()
  },
  methods: {
    dateFormat(data) {
      if (data) {
        return moment(data).format('YYYY-MM-DD')
      } else {
        return ''
      }
    },
    getSelectedRows(obj) {
      // 将值赋给
      this.form = {
        projectName: obj.row.projectName
      }
      const formateData = (data) => {
        return data.map((item) => {
          const { number, name, unit, contractWorkVolume, childrens, parentId, unitPrice, planFinishCount, planFinishAmount, thisMonthTotalFinishAmount } = item
          return {
            parentId,
            number,
            name,
            unit,
            ...(childrens
              ? {
                childrens: formateData(childrens)
              }
              : {}),
            contractWorkVolume: contractWorkVolume,
            contractPrice: '',
            contractAmount: '',
            costUnitPrice: unitPrice,
            planFinishCount: planFinishCount,
            planFinishAmount: planFinishAmount,
            preMonthTotalFinishAmount: thisMonthTotalFinishAmount, // 上月累计已完成金额 = 审批通过的项目月进度统计中本月累计已完成
            inputTax: '',
            finishCount: '',
            finishOutValue: '',
            cost: ''
          }
        })
      }
      this.targetList = formateData(obj.list)
    },
    provinceChange(e) {
      const selectedData = this.provinceData.filter((val) => val.name === e)[0]
      if (selectedData) {
        this.form.city = ''
        const params = {
          parentCode: selectedData.code,
          areaType: 2
        }
        getAreaList(params).then((res) => {
          this.cityData = res.data || []
        })
      }
    },
    getDocDetail(id) {
      getProjectScheduleStatInfoDetail({ projectScheduleStatInfoId: id }).then(
        (res) => {
          const { lstAttachment, lstProjectScheduleStatDetail } =
            res.data || {}
          if (lstAttachment && lstAttachment.length > 0) {
            this.fileList = lstAttachment
          }
          if (
            lstProjectScheduleStatDetail &&
            lstProjectScheduleStatDetail.length > 0
          ) {
            this.targetList = lstProjectScheduleStatDetail

            this.targetList.forEach((item, index) => {})
          }
        }
      )
    },
    getRegionData() {
      getAreaList({ areaType: '1' }).then((res) => {
        this.provinceData = res.data || []
      })
    },
    deleteDetail() {},
    saveDoc() {
      if (this.optType === 'detai') {
        this.show = false
        return
      }
      this.$refs.form.validate((valid) => {
        if (valid) {
          const params = {
            projectScheduleStatInfo: {
              ...this.form,
              ...(this.optType === 'edit'
                ? {
                  id: this.data.id
                }
                : {})
            },
            lstAttachment: this.fileList,
            lstProjectScheduleStatDetail: this.targetList
          }
          const fn =
            this.optType === 'add'
              ? addProjectScheduleStatInfo
              : updateProjectScheduleStatInfo
          fn(params).then((res) => {
            if (res.code === '0001') {
              this.$message({
                type: 'success',
                message: '保存成功!'
              })
              this.show = false
              this.$emit('freshList')
              this.$refs.form.resetFields()
            } else {
              this.$message({
                type: 'error',
                message: res.msg
              })
            }
          })
        }
      })
    },
    // 获取进税项合计
    getSumInputTax() {
      let sum = 0
      const formateData = (data) => {
        data.forEach(item => {
          if (item.childrens) {
            formateData(item.childrens)
          }
          if (item.inputTax) {
            sum += Number.parseFloat(item.inputTax)
          }
        })
      }
      formateData(this.targetList)
      this.form.totalInputTax = sum.toFixed(2)
      this.$forceUpdate()
    },
    // 获取本月完成金额汇总
    getSumThisMonthFinishAmount() {
      let sum = 0
      const formateData = (data) => {
        data.forEach(item => {
          if (item.childrens) {
            formateData(item.childrens)
          }
          if (item.thisMonthFinishAmount) {
            sum += Number.parseFloat(item.thisMonthFinishAmount)
          }
        })
      }
      formateData(this.targetList)
      this.form.thisMonthCompleteAmount = sum.toFixed(2)
      this.$forceUpdate()
    },
    // 获取本月完成金额
    getThisMonthFinishAmount() {
      let thisMonthFinishCount = 0
      let costUnitPrice = 0
      if (this.selectRow.thisMonthFinishCount) {
        thisMonthFinishCount = this.selectRow.thisMonthFinishCount
      }
      if (this.selectRow.costUnitPrice) {
        costUnitPrice = this.selectRow.costUnitPrice
      }
      const thisMonthFinishAmount = Number.parseFloat(costUnitPrice) * Number.parseFloat(thisMonthFinishCount)
      this.selectRow.thisMonthFinishAmount = thisMonthFinishAmount.toFixed(2)
      // 获取进度偏差额
      this.getProgressDeviation()
      // 获取本月完成金额汇总
      this.getSumThisMonthFinishAmount()
      // 获取本月累计已完成金额
      this.getThisMonthTotalFinishAmount()
    },
    // 获取本月累计已完成金额
    getThisMonthTotalFinishAmount() {
      let thisMonthFinishCount = 0
      let preMonthTotalFinishAmount = 0
      if (this.selectRow.preMonthTotalFinishAmount) {
        preMonthTotalFinishAmount = this.selectRow.preMonthTotalFinishAmount
      }
      if (this.selectRow.thisMonthFinishCount) {
        thisMonthFinishCount = this.selectRow.thisMonthFinishCount
      }
      const thisMonthTotalFinishAmount = Number.parseFloat(thisMonthFinishCount) + Number.parseFloat(preMonthTotalFinishAmount)
      this.selectRow.thisMonthTotalFinishAmount = thisMonthTotalFinishAmount.toFixed(2)
    },
    // 获取进度偏差额汇总
    getSumProgressDeviation() {
      let sum = 0
      const formateData = (data) => {
        data.forEach(item => {
          if (item.childrens) {
            formateData(item.childrens)
          }
          if (item.progressDeviation) {
            sum += Number.parseFloat(item.progressDeviation)
          }
        })
      }
      formateData(this.targetList)
      this.form.progressDeviation = sum.toFixed(2)
      this.$forceUpdate()
    },
    // 获取计划完成金额汇总
    getSumPlanCompleteAmount() {
      let sum = 0
      const formateData = (data) => {
        data.forEach(item => {
          if (item.childrens) {
            formateData(item.childrens)
          }
          if (item.planFinishAmount) {
            sum += Number.parseFloat(item.planFinishAmount)
          }
        })
      }
      formateData(this.targetList)
      this.form.planCompleteAmount = sum.toFixed(2)
      this.$forceUpdate()
    },
    // 获取进度偏差额
    getProgressDeviation() {
      let thisMonthFinishAmount = 0
      let planFinishAmount = 0
      if (this.selectRow.thisMonthFinishAmount) {
        thisMonthFinishAmount = this.selectRow.thisMonthFinishAmount
      }
      if (this.selectRow.planFinishAmount) {
        planFinishAmount = this.selectRow.planFinishAmount
      }
      const progressDeviation = Number.parseFloat(thisMonthFinishAmount) - Number.parseFloat(planFinishAmount)
      this.selectRow.progressDeviation = progressDeviation.toFixed(2)
      // 获取进度偏差额汇总
      this.getSumProgressDeviation()
      // 获取计划完成金额汇总
      this.getSumPlanCompleteAmount()
    }
  }
}
</script>

<style lang="scss" scoped>
.com-form-title {
  font-size: 14px;
  font-weight: bold;
  line-height: 35px;
  color: #409eff;
  border-bottom: 1px solid #dedede;
  margin-bottom: 6px;
}
</style>
